package com.wangyadong.hobby.schedule.jobtask.tree.example1;

import com.wangyadong.hobby.schedule.jobtask.tree.Position;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractBinaryTree <E>extends AbstarctTree implements BinaryTree {
    @Override
    public Iterable<Position> child(Position position) throws IllegalArgumentException {
        List<Position> list = new ArrayList<>();
        if (left(position) != null) {
            list.add(left(position));
        }
        if (right(position) != null) {
            list.add(right(position));
        }

        return list;
    }

    @Override
    public int childNum(Position position) throws IllegalArgumentException {
        int count = 0;
        if (left(position) != null) {
            ++count;
        }
        if (right(position) != null) {
            ++count;
        }
        return count;
    }

    @Override
    public Position sibling(Position position) throws IllegalArgumentException {
        Position parent = parent(position);
        if (null == parent) {
            return null;
        }
        if (position == left(parent)) {
            return right(parent);
        } else {
            return left(parent);
        }
    }
}
